package com.kuangstudy.thread.advanced;

/**
 * @author Losca
 * @date 2021/7/22 14:18
 * 测试生产者和消费者
 */
public class TestPc {
    public static void main(String[] args) {
        SynContainer container = new SynContainer();
        new Product(container).start();
        new Consumer(container).start();
    }
}
//生产者
class Product extends Thread{

    SynContainer container;

    public Product(SynContainer container){
        this.container = container;
    }

    //生产
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            container.push(new Chicken(i));
            System.out.println("生产了"+i+"只鸡");
        }
    }
}

//消费者
class Consumer extends Thread{
    SynContainer container;
    public Consumer(SynContainer container){
        this.container = container;
    }
    //消费
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消费了=>"+container.pop().id+"只鸡");
        }
    }
}

//鸡
class Chicken {
    int id;

    public Chicken(int id) {
        this.id = id;
    }
}

//容器
class SynContainer{
    Chicken[] chickens = new Chicken[10];
    int count = 0;
    //生产者放入产品
    public synchronized void push(Chicken chicken){
        //容器满了通知消费者消费
        if (count == chickens.length){
            //生产停止 通知消费者消费
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        chickens[count] = chicken;
        count++;
        //可以通知消费者消费了
        this.notifyAll();
    }

    //消费者消费产品
    public synchronized Chicken pop(){
        //没鸡了等待生产者生产
        if (count == 0){
            //消费停止 通知生产者生产
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count--;
        Chicken chicken = chickens[count];
        //吃完了通知生产者生产
        this.notifyAll();
        return chicken;
    }
}